import Vue from 'vue'
import Router from 'vue-router'
import routes from './routers'
import {
  endRouter
} from './routers'


import store from '@/store'
import iView from 'iview'

import {
  loadMenu
} from '@/libs/router-util' //路由
import {
  message
} from '@/libs/resetMessage';
import {
  setToken,
  getToken,
  canTurnTo,
  setTitle
} from '@/libs/util'
import config from '@/config'

const {
  homeName
} = config
import Main from '@/components/main' //cj
Vue.use(Router);

const router = new Router({
  routes: routes,
  mode: 'hash'

})

 // 递归添加路由
const addrouteFun = (data) => {
  let _this = this;
  data.forEach(function(cv, i) {
    let name=cv.path.substring(1,cv.path.length);
    router.addRoute(name, cv);//cv.name
    if (cv.children && cv.children.length) {
      addrouteFun(cv.children)
    }
  })

  return data
}
// 页面刷新的时候重新添加路由
let back = [...loadMenu(), ...endRouter];

addrouteFun(back)

// back.forEach(function(cv, i) {
//   router.addRoute(cv.name, cv);
//   if (cv.children && cv.children.length) {
//     cv.children.forEach(function(row) {
//       router.addRoute(cv.name, row);
//     })
//   }
// })

const LOGIN_PAGE_NAME = 'login'

const turnTo = (to, access, next) => {
  if (canTurnTo(to.name, access, routes)) next() // 有权限，可访问
  else next({
    replace: true,
    name: 'error_401'
  }) // 无权限，重定向到401页面
}
router.beforeEach((to, from, next) => {
  // 页面刷新cj
  iView.LoadingBar.start()
  const token = getToken();

  if (!token && to.name !== LOGIN_PAGE_NAME) {
    // 未登录且要跳转的页面不是登录页
    message({
      type: 'error',
      message: '登录已经过期，请重新登录！'
    })
    next({
      name: LOGIN_PAGE_NAME // 跳转到登录页
    })
  } else if (!token && to.name === LOGIN_PAGE_NAME) {
    // 未登陆且要跳转的页面是登录页
    next() // 跳转
  } else if (token && to.name === LOGIN_PAGE_NAME) {
    // 已登录且要跳转的页面是登录页
    next({
      name: homeName // 跳转到homeName页
    })
  } else {
    next()
  }
})

router.afterEach(to => {
  setTitle(to, router.app)
  iView.LoadingBar.finish()
  window.scrollTo(0, 0)
})

export default router
